<template>
    <div class="page-wrap">
        <div class="page-header-wrap">
            <a-page-header @back="handleBack">
                <template #subTitle>
                    <span style="color: #000; font-size: 20px">{{ $route.query.productCatalogName }}{{ $route.query.subProductCatalogName ? `-${$route.query.subProductCatalogName}` : '' }}</span>
                </template>
                <div style="width: calc(100% - 130px)">
                    <a-form layout="inline">
                        <a-row>
                            <a-col :span="10">
                                <a-form-item label="产品负责人" :span="24">
                                    <span>{{ positionObj['产品经理'] }}</span>
                                </a-form-item>
                            </a-col>
                            <a-col :span="10">
                                <a-form-item label="测试经理" :span="24">
                                    <span>{{ positionObj['测试经理'] }}</span>
                                </a-form-item>
                            </a-col>
                            <a-col :span="3">
                                <a-button @click="handleOpenHistoryModal">操作历史</a-button>
                            </a-col>
                        </a-row>
                    </a-form>
                </div>
            </a-page-header>
        </div>
        <div style="background: #fff; width: 100%; padding: 12px">
            <h-section title="特性树">
                <div class="margin-b-16">
                    <flexbox>
                        <div>
                            <a-input-search placeholder="请输入名称" style="width: 300px" enter-button @search="handleSearch" />
                        </div>
                        <a-button @click="handleAddRootNode" type="primary" class="margin-l-16">新增根节点</a-button>

                        <a-dropdown :trigger="['click']">
                            <template #overlay>
                                <a-menu>
                                    <a-menu-item key="1">
                                        <span @click="handleDownTemplate">
                                            <DownloadOutlined />
                                            下载模板
                                        </span>
                                    </a-menu-item>
                                    <a-menu-item key="2">
                                        <a-upload a-upload name="file" :showUploadList="false" :customRequest="handleUpdoadingFile" :beforeUpload="handleBeforeUpload">
                                            <UploadOutlined />
                                            导入数据
                                        </a-upload>
                                    </a-menu-item>
                                </a-menu>
                            </template>
                            <a-button type="primary" class="margin-l-16"> 模板导入</a-button>
                        </a-dropdown>
                    </flexbox>
                </div>

                <a-tree :autoExpandParent="autoExpandParent" v-model:expandedKeys="expandedKeys" :replaceFields="{ children: 'subNodes', key: 'id', title: 'nodeName' }" :tree-data="treeData">
                    <template v-slot:title="{ nodeName, id, parentId, nodeOrder }">
                        <flexbox class="title-wrap">
                            <span v-if="nodeName.indexOf(searchValue) > -1">
                                {{ nodeName.substr(0, nodeName.indexOf(searchValue)) }}
                                <span style="color: #f50">{{ searchValue }}</span>
                                {{ nodeName.substr(nodeName.indexOf(searchValue) + searchValue.length) }}
                            </span>
                            <span v-else>{{ nodeName }}</span>
                            <!-- 阶段和状态节点或者阶段和状态下的子节点无法修改和新增 -->
                            <div class="icon-cont margin-l-8">
                                <PlusOutlined @click.stop="handleCreate({ parentId: id, parentName: nodeName, nodeOrder })" />
                                <EditOutlined @click.stop="handleEdit({ id, parentId, nodeName, nodeOrder })" style="margin-left: 2px" />
                                <CloseOutlined @click.stop="handleDelete({ id, nodeName })" style="margin-left: 2px" />
                            </div>
                        </flexbox>
                    </template>
                </a-tree>
            </h-section>
        </div>
        <AddModal ref="AddModalRef" @success="getTreeData" />
        <HistoryRecordModal ref="HistoryRecordModalRef" />
    </div>
</template>

<script lang="ts">
import { useDownFile } from '@/hooks/common/useFile';
import { useMessage } from '@/hooks/common/useMessage';
import HistoryRecordModal from '@/views/productAnalysis/texingTree/components/HistoryRecordModal.vue';
import AddModal from './components/AddModal.vue';
import { useRouterApi } from '@/hooks/common/useRouterApi';
import { transformToList, getParentKey, getParent } from '@/utils/tree';
import { UploadOutlined, PlusOutlined, EditOutlined, CloseOutlined, DownloadOutlined } from '@ant-design/icons-vue';
import { message } from 'ant-design-vue/es';
import { transformDataByFlatProperty } from '@/utils/tree';
import api from '@/api';
import { defineComponent, ref, unref, reactive, toRefs } from 'vue';
export default defineComponent({
    components: {
        UploadOutlined,
        PlusOutlined,
        DownloadOutlined,
        EditOutlined,
        CloseOutlined,
        AddModal,
        HistoryRecordModal
    },
    setup() {
        const { downTemplate } = useDownFile();
        const AddModalRef = ref<any>();
        const HistoryRecordModalRef = ref<any>();
        const { route, handleBack } = useRouterApi({
            backQuery: {
                path: '/productAnalysis/texingTree'
            }
        });
        const state = reactive<any>({
            treeData: [],
            positionObj: {
                产品经理: '',
                测试经理: ''
            },
            searchValue: '',
            catalogCode: '',
            expandedKeys: [],
            autoExpandParent: false
        });
        const getTreeData = async () => {
            const query = {
                catalogCode: state.catalogCode
            };
            const { success, moule } = await api.texingTreeModel.getTreeData(query);
            if (success) {
                state.treeData = [...transformDataByFlatProperty(moule)];
            }
        };

        const handleSearch = (val: string) => {
            const dataList = transformToList(state.treeData, {
                keyField: 'id',
                titleField: 'nodeName',
                childrenField: 'subNodes'
            });
            const expandedKeys = dataList
                .map((item: any) => {
                    if (item.nodeName.indexOf(val) > -1) {
                        return getParentKey(item.id, state.treeData, {
                            keyField: 'id',
                            childrenField: 'subNodes'
                        });
                    }
                    return null;
                })
                .filter((item, i, self) => item && self.indexOf(item) === i);
            state.searchValue = val;
            state.expandedKeys = expandedKeys;
            state.autoExpandParent = true;

            console.log(val, expandedKeys);
        };
        const uploadFile = (options: any) => {
            const name = options.file.name.replace(/[?？*<>()（）{}$&:："“”|\\/\\[\]【】]/gi, '');
            const file: any = new File([options.file], name);
            // console.log(file);
            const formData: any = new FormData();
            formData.append('file', file);
            formData.append('catalogCode', state.catalogCode);
            const config = {
                cancelDuplicated: true //取消重复检测
            };
            api.texingTreeModel
                .init(formData, config)
                .then((res) => {
                    // 可能会出现超时
                    if (res.success) {
                        message.success(`${options.file.name}上传成功`);
                        getTreeData();
                        options.onSuccess(res, options.file); //这个会添加response信息字段
                    } else {
                        message.error(`${options.file.name}上传失败`);
                    }
                })
                .catch(() => {
                    options.onError(); //这个会添加response和error信息字段，status会从uploading变为error
                    message.error(`${options.file.name}上传失败`);
                });
        };
        const handleUpdoadingFile = (options: any) => {
            if (state.treeData && state.treeData.length) {
                const { createConfirm } = useMessage();
                createConfirm({
                    title: '导入后删除原有树,是否继续导入？',
                    iconType: 'danger',
                    onOk: async () => {
                        uploadFile(options);
                    }
                });
            } else {
                uploadFile(options);
            }
        };
        // 上传前检测大小
        const handleBeforeUpload = (file): boolean => {
            const size: number = file.size;
            const max = 60;
            // 不能带有[]符号
            // if (/[*<>(){}$&?:"|\\/\\[\]]/gi.test(file.name)) {
            //     message.error('上传文件名称不能带有特殊符号：<>(){}$&?:|/\\[]');
            //     return false;
            // }
            if (size / 1024 / 1024 > max) {
                message.error('上传文件过大');
                return false;
            }

            return true;
        };

        const handleOpenHistoryModal = () => {
            unref(HistoryRecordModalRef).open(state.catalogCode);
        };

        const handleCreate = (query) => {
            unref(AddModalRef).open({
                ...query,
                catalogCode: state.catalogCode
            });
        };

        const handleAddRootNode = () => {
            unref(AddModalRef).open({
                catalogCode: state.catalogCode
            });
        };

        const handleEdit = (query) => {
            const node: any = getParent(query.id, state.treeData, {
                keyField: 'id',
                childrenField: 'subNodes'
            });
            console.log(node);
            unref(AddModalRef).open({
                ...query,
                parentName: node ? node.nodeName : '',
                catalogCode: state.catalogCode
            });
        };

        const handleDelete = (record) => {
            const { createConfirm } = useMessage();
            createConfirm({
                title: `确认删除【${record.nodeName}】?`,
                iconType: 'danger',
                onOk: async () => {
                    const query = {
                        id: record.id
                    };
                    const { success, errorMsg } = await api.texingTreeModel.delete(query);
                    if (success) {
                        message.success('删除成功');
                        getTreeData();
                    } else {
                        message.error(errorMsg);
                    }
                }
            });
        };
        const handleDownTemplate = () => {
            downTemplate('character_tree');
        };
        const getPosition = async (position) => {
            const { success, moule } = await api.texingTreeModel.getBySystemIdAndPosition({
                catalogCode: state.catalogCode,
                position
            });
            if (success) {
                if (moule && moule.length) {
                    state.positionObj[position] = moule.map((item) => item.empName).join(',');
                }
            }
        };
        const getPositions = () => {
            getPosition('产品经理');
            getPosition('测试经理');
        };
        const init = () => {
            state.catalogCode = route.query.catalogCode;
            getTreeData();
            getPositions();
        };
        init();
        return {
            AddModalRef,
            HistoryRecordModalRef,
            ...toRefs(state),
            handleBack,
            handleBeforeUpload,
            handleUpdoadingFile,
            handleSearch,
            handleCreate,
            handleEdit,
            handleDelete,
            handleOpenHistoryModal,
            getTreeData,
            handleAddRootNode,
            handleDownTemplate
        };
    }
});
</script>

<style scoped lang="less">
.page-wrap {
    position: relative;
    height: 100%;
    .page-header-wrap {
        background: #fff;
        position: sticky;
        top: 0;
        z-index: 9;
        border-bottom: 1px solid #f1f1f1;
        border-top: 1px solid #f1f1f1;
        margin-bottom: 24px;
        &::before {
            content: '';
            position: absolute;
            width: 6px;
            height: 100%;
            background: #3094e9;
            top: 0;
            left: 0;
            z-index: 1;
        }
        .extra-wrap {
            position: absolute;
            right: 40px;
            bottom: 22px;
            color: #000;
            cursor: pointer;
        }
    }
}
.section-wrap {
    padding: 0;
}
// // 去掉表头颜色
::v-deep(.ant-table-thead) > tr > th {
    background: #eaf5fe !important;
    font-weight: 400;
    color: @primary-color;
}
::v-deep(.ant-divider) {
    border-top: 2px solid #eaf5fe;
}
::v-deep(.zoom-container) {
    width: 100%;
    display: flex;
    flex-direction: column;
    justify-content: center;
    align-items: center;
}
</style>